package forkjoin;

import java.util.concurrent.ExecutionException;
import java.util.concurrent.ForkJoinPool;
import java.util.concurrent.ForkJoinTask;
import java.util.stream.LongStream;

//1-10_0000_0000的求和
//1.正常方法求和  2.forkjoin  3.并行流计算
public class ForkJoinDemo {
    public static void main(String[] args) throws ExecutionException, InterruptedException {
        test1();//11755ms
        test2();//6398ms
        test3();//508ms
    }
    //普通程序员
    public  static void test1(){
        Long sum = 0L;
        long start = System.currentTimeMillis();
        for (Long i = 1L; i <=10_0000_0000 ; i++) {
            sum+=i;
        }
        long end = System.currentTimeMillis();
        System.out.println("sum== "+sum+" time=="+(end-start));
    }
    //中级程序员 forkjoin
    public static void test2() throws ExecutionException, InterruptedException {
        long start = System.currentTimeMillis();
        ForkJoinPool pool = new ForkJoinPool();
        ForkJoinBean fork = new ForkJoinBean(0L,10_0000_0000L);
        ForkJoinTask<Long> task = pool.submit(fork);
        Long sum = task.get();
        long end = System.currentTimeMillis();
        System.out.println("sum== "+sum + " "+(end-start));
    }
    //高级程序员
    public static void test3(){
        long start = System.currentTimeMillis();
        long sum = LongStream.rangeClosed(0L, 10_0000_0000L).parallel().reduce(0,Long::sum);
        long end = System.currentTimeMillis();
        System.out.println("sum== " + sum + " " + (end - start));
    }
}
